<template>
	<view class="content">
		<view class="width-full" :style="{
			  backgroundImage: `url('${bgpic}')`,
			  backgroundSize: '100% 100%',
			  height:'480rpx'
			}">
			<view class="arr" @click='beforeleave'>
				<up-icon name="arrow-left" color="#fff" size="20"></up-icon>
			</view>

		</view>

		<view class="story-main box-sizing" style='padding: 20rpx 30rpx;'>
			<view class="text-right fontSize-28 color-666">
				{{list.time}}
			</view>
			<view class="fontSize-28 color-333 weight-700 marginTop-32">
				<span v-html='list.english_story'></span>
			</view>
			<image :src="list.story_pics" mode="" class="story-img"
				style="width: 200rpx; height: 200rpx;border-radius: 20rpx;" @click='imgShow = true'>
			</image>
			<up-overlay :show="imgShow" @click="imgShow = false">
				<view class="warp">
					<image :src="list.story_pics" mode="" style="width: 100%; height: 100vh;"></image>
				</view>
			</up-overlay>
			<!-- 	<view class="" @click="playVoice">
				播放
			</view> -->
			<view class="">
				<view class="" v-if='isFinish == true'>
					<!-- 调速拉条区 -->
					<view class="audio-progress">
						<!-- <image src="./icon/get-back.svg" @click="onSeek(-15)"></image> -->
						<view class="audio-bar">
							<up-slider v-model="currentTime" activeColor="#00CA86" :min="0" :max="duration"
								block-color="#00CA86" block-size="18" @change="sliderChange" @changing="sliderChanging">
							</up-slider>
						</view>
					</view>
					<!-- 显示时间进度区 -->
					<view class="bar-tips">
						<text>{{minTimeFmt(currentTime)}}</text>
						<text>{{minTimeFmt(duration)}}</text>
					</view>
					<!-- 按钮区 -->
					<view class="audio-btn">
						<view class="play-box">
							<view class="play-btn" :style="{backgroundColor:isPaused?'#00CA86':'#475266'}"
								@click="onPlayPause">
								<image v-show="isPaused" src="../../static/image/suspend.svg"></image>
								<image v-show="!isPaused" src="../../static/image/start.svg"></image>
							</view>
						</view>
					</view>
					<!-- <le-audio :activeIndex="0" :audioData="audioList"
						 :autoplay="false" v-if='isFinish == true'></le-audio> -->
				</view>
			</view>
		</view>
		<view class="btn" @click='startRecord' v-if='isSpeak == false&&isFinish == false'>
			点击讲故事
		</view>

		<view class="btn" @click.stop='upLoad' v-if='isFinish == true&&isOnload == false'>
			上传
		</view>

		<view class="btn" v-if='isFinish == true&&isOnload == true' @click='deleteShow = true'>
			重新录制
		</view>
		<view class="speak-block" v-if='isSpeak == true'>
			<view class="width-160 height-40" style="margin: 0 auto;">
				<image src="http://bbsf.oss-cn-shanghai.aliyuncs.com/english/my/20241112-170350.gif" mode=""
					style="width: 100%;height: 100%;"></image>

			</view>
			<view class="color-white text-center marginTop-10">
				录音中...
			</view>
			<view class="marginTop-52 flex space-between">
				<view class="btn1" @click.stop='cancel'>
					取消
				</view>
				<view class="btn1" style="background: #51D580;" @click.stop='endRecord'>
					完成
				</view>
			</view>
		</view>
		<!-- 删除弹窗 -->
		<up-popup :show="deleteShow" mode='center' bgColor='transparent'>
			<view class="popup_bg">
				<view class="color-white fontSize-52 text-center marginTop-25">
					温馨提示
				</view>
				<view class="text-center marginTop-120 paddingLeft-30 paddingRight-30">
					重新录制将替换您上一次录制的故事，确认录制吗？
				</view>

				<view class="flex space-between items-center padding-30 marginTop-20">
					<view class="btn-block" @click="deleteShow = false">
						取消
					</view>
					<view class="btn-block" @click="deleteSrc" style="background: #51D580;">
						删除
					</view>
				</view>
			</view>
		</up-popup>
		<!-- 返回弹窗 -->
		<up-popup :show="backShow" mode='center' bgColor='transparent'>
			<view class="popup_bg">
				<view class="color-white fontSize-52 text-center marginTop-25">
					温馨提示
				</view>
				<view class="text-center marginTop-120 paddingLeft-30 paddingRight-30">
					别放弃，坚持就是胜利！ 后面的训练趣味十足
				</view>

				<view class="flex space-between items-center padding-30 marginTop-20">
					<view class="btn-block" @click="toPage">
						退出
					</view>
					<view class="btn-block" @click="backShow = false" style="background: #51D580;">
						继续
					</view>
				</view>
			</view>
		</up-popup>
		<!-- 完成弹窗 -->
		<up-popup :show="finishShow" mode='center' bgColor='transparent'>
			<view class="popup_bg bg2">
				<view class="color-666 fontSize-28 text-center marginTop-250">
					这是你录制的第{{finish_num}}篇故事了，大批志同道合的朋友正在朝你涌来！
				</view>
				<view class="text-center marginTop-36 fontSize-32 weight-700">
					小家单词训练已完成，快来看看你的学习报告吧!
				</view>
				<view @click="toStudyReport()" class="btn-block">
					去看看
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		inject,
		onMounted,
		reactive
	} from 'vue';
	import {
		onLoad,
		onUnload,
		onHide
	} from '@dcloudio/uni-app';
	const getStoryInfoApi = inject('getStoryInfo')
	const speakRemStoryApi = inject('speakRemStory')
	const page = ref(1)
	const big_sort = ref(1)
	const small_sort = ref(1)
	const list = ref({})
	const bgpic = ref('')
	const story_audio = ref('')
	const deleteShow = ref(false)
	const backShow = ref(false)
	const finishShow = ref(false)
	const imgShow = ref(false)
	const isOnload = ref(false)

	const isShowPage = ref(true)

	const finish_num = ref(1)


	// 创建录音管理器实例的引用

	const recorderManager = ref(null);
	// 创建内部音频上下文实例的引用
	const innerAudioContext = uni.createInnerAudioContext();
	// 创建存储录音文件路径的变量
	const audioUrl = ref('');
	const isSpeak = ref(false)
	const isOpen = ref(false)
	const isFinish = ref(false)
	const duration = ref(0);
	const audioList = ref([])
	// 音频时间
	const timer = ref(null);
	// 状态
	const audioStatus = ref(false);
	//重置
	const reset = ref(false);
	//播放状态
	const isPlaying = ref(false);
	onUnload(() => {
		innerAudioContext.destroy()
		// innerAudioContext = null
		if (timer.value) clearInterval(timer.value);
		if (recorderManager.value) recorderManager.value.stop();
	})
	onHide(() => {
		innerAudioContext.destroy()
		// innerAudioContext = null
		if (timer.value) clearInterval(timer.value);
		if (recorderManager.value) recorderManager.value.stop();
	})
	onLoad((op) => {
		page.value = op.page
		big_sort.value = op.big_sort
		small_sort.value = op.small_sort
		getStoryInfoApi({
			page: page.value,
			big_sort: big_sort.value,
			small_sort: small_sort.value

		}).then(res => {
			list.value = res
			bgpic.value = res.bgpic
			story_audio.value = res.story_audio
			duration.value=res.duration
			if (res.story_audio != '') {
				isFinish.value = true
				isOnload.value = true
				innerAudioContext.src = res.story_audio
			}
		})

		uni.authorize({
			scope: 'scope.record',
			success() {
				uni.getRecorderManager()
				console.log('成功')
			}
		})


	})
	// 在组件挂载后绑定音频播放结束事件监听
	onMounted(() => {
		innerAudioContext.onEnded(onAudioEnded);
	});

	// 监听录音状态变化  
	const handleStart = () => {
		console.log('录音开始');
		audioStatus.value = true;

	};

	// 监听录音停止  
	const handleStop = (res) => {
		console.log('录音停止', res.tempFilePath);
		if (!reset.value) {
			audioUrl.value = res.tempFilePath;
		} else {
			audioUrl.value = '';
		}
		audioStatus.value = false;
			isPaused.value = true;
	};





	// 开始录音的函数
	const startRecord = () => {
		console.log('开始录音11');
		recorderManager.value = uni.getRecorderManager()
		recorderManager.value.start({
			format: 'mp3'
		});
		recorderManager.value.onStart(handleStart);
		recorderManager.value.onStop(handleStop);
		isSpeak.value = true
	};
	const playVoice = () => {
		console.log('播放录音');
		innerAudioContext.value.src = audioList.value;
		innerAudioContext.play();
	};
	// 录音结束的函数
	const totalDuration = ref(0)
	const currentTime = ref(0) //当前时长
	const percentage = ref(100)
	const isPaused = ref(true)
	const minTimeFmt = (val) => {
		let minute = parseInt(val / 60);
		let seconds = Math.ceil(val % 60)
		return `${minute>=10?minute:'0'+minute}:${seconds>=10?seconds:'0'+seconds}`
	};

	const endRecord = () => {
		recorderManager.value.stop();
		isSpeak.value = false;
		isFinish.value = true;
		isOnload.value = false
		console.log('录音结束11');
		recorderManager.value.onStop((res) => {
			console.log(res, '获取res')
			totalDuration.value = Math.floor(res.duration / 1000)
			duration.value = totalDuration.value
			console.log(totalDuration.value, 999999999999)
			
			uni.uploadFile({
				url: $uploadHttp,
				filePath:  res.tempFilePath,
				name: 'file',
				// formData: {
				// 	'user': 'test'
				// },
				success: (uploadFileRes) => {
					console.log(JSON.parse(uploadFileRes.data));
					let data = JSON.parse(uploadFileRes.data)
					audioUrl.value = data.data;
				}
			});
			// innerAudioContext.src = audioUrl.value
			// innerAudioContext.play();
			// console.log(audioUrl.value, 291)
			// audioList.value.push(...[{
			// 	fileUrl: audioUrl.value
			// }])
		});
	};


	// 播放录音的函数
	const intervalId = ref(null)
	// 监听音频播放结束事件的函数
	const onAudioEnded = () => {
		console.log('音频播放结束');
		isPlaying.value = false;
		isOpen.value = false;
		percentage.value = 100
		currentTime.value = 0
			isPaused.value = true;
		if (timer.value) clearInterval(timer.value);
	}

	const cancel = () => {
		isSpeak.value = false
		console.log('取消录制11');
		recorderManager.value.stop();
	};
	const $uploadHttp = inject('$uploadHttp');
	const upLoad = () => {
		console.log('audioUrl.value', audioUrl.value)
		speakRemStoryApi({
			page: page.value,
			big_sort: big_sort.value,
			small_sort: small_sort.value,
			story_audio: audioUrl.value,
			duration:duration.value 

		}).then(res => {
			finish_num.value = res.finish_num
			finishShow.value = true
		})
	}

	const deleteSrc = () => {
		speakRemStoryApi({
			page: page.value,
			big_sort: big_sort.value,
			small_sort: small_sort.value,
			story_audio: ''

		}).then(res => {
			deleteShow.value = false
			isFinish.value = false
		})
	}

	const beforeleave = (e) => {
		backShow.value = true
	}
	const toPage = () => {
		backShow.value = false
		uni.navigateBack()

	}
	const toStudyReport = () => {
		uni.redirectTo({
			url: "/pagesA/reciteWords/myStudyReport?big_sort=" +
				big_sort.value +
				"&page=" +
				page.value +
				"&small_sort=" +
				small_sort.value
		});

	}
	const isSlidering = ref(false) //是否移动中
	// 录音播放暂停
	// 滑块滚动到的位置
	const sliderChange = (e) => {
		isSlidering.value = false;
		currentTime.val = e.detail.value;
		innerAudioContext.seek(e.detail.value);
	}
	// 滑块滚动到的位置 实时
	const sliderChanging = (e) => {
		isSlidering.value = true;
		currentTime.val = e.detail.value;
	}
	// 暂停播放切换
	const onPlayPause = () => {
		if (isPaused.value) {
			timer.value = setInterval(() => {
				currentTime.value++;
			}, 1000);
			innerAudioContext.src = audioUrl.value
			innerAudioContext.play()
			isPaused.value = false;
		} else {
			innerAudioContext.pause()
			isPaused.value = true;
			if (timer.value) clearInterval(timer.value);
		}
	}
</script>

<style scoped lang="scss">
	.content {
		height: 100%;
	}

	.story-main {
		width: 686rpx;
		height: 976rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 8rpx 30rpx 0rpx rgba(0, 0, 0, 0.05);
		border-radius: 30rpx 30rpx 30rpx 30rpx;
		margin: 0 auto;
		margin-top: -100rpx;
		position: relative;
	}

	.btn {
		width: 702rpx;
		height: 104rpx;
		background: #51D580;
		border-radius: 92rpx 92rpx 92rpx 92rpx;
		text-align: center;
		line-height: 104rpx;
		color: #FFFFFF;
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.story-img {
		margin-top: 400rpx;
	}

	@media (max-height: 800px) {
		.btn {

			bottom: 10rpx;

		}

		.story-main {

			height: 800rpx;

		}

		.story-img {
			margin-top: 200rpx;
		}
	}

	.speak-block {
		width: 100%;
		height: 400rpx;
		// background: rgba(0, 0, 0, 0.6);
		background-color: #999;
		position: fixed;
		bottom: 0;
		left: 0;
		padding: 50rpx 24rpx;
		box-sizing: border-box;

	}

	.btn1 {
		width: 340rpx;
		height: 104rpx;
		background: #CCCCCC;
		border-radius: 92rpx 92rpx 92rpx 92rpx;
		text-align: center;
		line-height: 104rpx;
		color: #FFFFFF;
	}

	.upload-section {
		position: absolute;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.upload-block {
		width: 626rpx;
		height: 90rpx;
		background: #F5F5F5;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		padding: 22rpx;
		box-sizing: border-box;
		margin: 10rpx auto;
	}



	.popup_bg {
		width: 610rpx;
		height: 500rpx;
		background: url('https://bbsf.oss-cn-shanghai.aliyuncs.com/english/icons/remind.png') no-repeat;
		background-size: 100% 100%;
		overflow: hidden;

		.btn-block {
			width: 252rpx;
			height: 92rpx;
			background: #CCCCCC;
			border-radius: 74rpx;
			text-align: center;
			line-height: 92rpx;
			color: #fff;
		}

	}

	.popup_bg.bg2 {
		width: 574rpx;
		height: 676rpx;
		background: url('https:\/\/bbsf.oss-cn-shanghai.aliyuncs.com\/english\/jiword\/zswc.png') no-repeat;
		background-size: 100% 100%;
		padding: 32rpx;
		box-sizing: border-box;

		.btn-block {
			width: 100%;
			background: #51D580;
			margin-top: 80rpx;
		}
	}

	.arr {
		position: absolute;
		left: 22rpx;
		top: 120rpx;
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.audio-content {
		width: 100vw !important;
		padding: 0 64rpx !important;
		box-sizing: border-box;
	}

	.audio-progress {
		display: flex;
		align-items: center;
		justify-content: space-between;


		.audio-bar {
			flex: 1;
			padding: 0 26rpx;
			box-sizing: border-box;

			.audio-slider {
				margin: 0 !important;
			}
		}
	}

	.bar-tips {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 74rpx;
		margin-bottom: 32rpx;
		color: #B8BECC;
		font-size: 24rpx;
		line-height: 10rpx;
	}

	.audio-btn {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 64rpx;

		image {
			width: 48rpx;
			height: 48rpx;
		}

		.play-box {
			display: flex;
			align-items: center;
			position: relative;
			left: 50%;
			transform: translateX(-50%)
		}

		.play-btn {
			width: 96rpx;
			height: 96rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0 64rpx;
			background: #475266;
			border-radius: 50%;

			image {
				width: 96rpx;
				height: 96rpx;
			}
		}

		.play-list-text {
			position: absolute;
			bottom: 0;
			left: -14rpx;
			color: #475266;
			font-size: 20rpx;
		}

		.speed-text {
			position: absolute;
			top: 20rpx;
			right: 0;
			color: #475266;
			font-size: 16rpx;
			font-weight: 600;
		}
	}
</style>
<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>